<?php
declare (strict_types = 1);
namespace app\admin\controller;

use Exception;
use think\Request;
use think\facade\{Db, View, Session};
use think\exception\ValidateException;

use app\admin\validate\{CouponValidate, CardShopValidate, GiftValidate};

use app\admin\model\{Admin, Cate, Goods, Coupon, CardShop, Gift, GiftGoods, Card};

class CouponController extends BaseController
{
    // 渲染优惠券列表页面
    public function coupon_list()
    {   
        return view();
    }

    // 渲染优惠券添加页面
    public function coupon_add()
    {   
        $adminModel = new Admin();

        $shopList = $adminModel->getList(['role_id' => 2], 0);

        View::assign('shop_list', $shopList['data']);
        return view();
    }

    // 渲染优惠券编辑页面
    public function coupon_edit()
    {   
        $data = input('get.');
        $adminModel = new Admin();
        $couponModel = new Coupon();

        $info = $couponModel->getFind(['id' => $data['id']])['data'];

        $scopeArr = $info->getData('scope');
        $scopeArr = explode(',', $scopeArr);
        array_pop($scopeArr);

        $info['scope_arr'] = $scopeArr;
        $info['scope_all'] = [1 => '实体店', 2 => '线上', 3 => '会员专享'];

        $shopList = $adminModel->getList([['id', '<>', $info->getData('admin_id')], ['role_id', '=', 2]], 0);

        View::assign('info', $info);
        View::assign('shop_list', $shopList['data']);
        return view();
    }

    // 获取优惠券列表
    public function coupon_data()
    {   
        $couponModel = new Coupon();
        $data = input('get.');

        // 验证数据
        try{
            validate(CouponValidate::class)->scene('list')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $where[] = ['del_time', '=', 0];

        // 搜索条件
        if($data && isset($data['key'])){
            if(!empty($data['key']['name'])){
                $where[] = ['name', 'like', '%' . $data['key']['name'] . '%'];
            }
        }

        $count = $couponModel->getNum($where)['data'];

        $field = 'id, admin_id, name, price, scope, is_show, start_time, end_time';
        $list = $couponModel->getList($where, 1, $data['page'], $data['limit'], $field);

        if($list['code'] != 'ok'){
            $this->error_back('暂无数据~');
        }

        $this->success_back('ok', $list['data'], $count);
    }

    // 是否销售的开启和关闭
    public function setIsShow()
    {
        $id = input('post.id');
        $couponModel = new Coupon();
        $isShow = $couponModel->setIsShow($id);

        $this->success_back($isShow['msg']);
    }

    // 优惠券添加
    public function couponAdd()
    {   
        $couponModel = new Coupon();
        $data = input('post.');

        // 验证数据
        try{
            validate(CouponValidate::class)->scene('add')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $data['start_time'] = strtotime($data['start_time']);
        $data['end_time']   = strtotime($data['end_time']);
        $flag = $couponModel->add($data);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('添加成功');
    }

    // 优惠券信息修改
    public function setCouponEdit()
    {   
        $couponModel = new Coupon();
        $data = input('post.');

        // 验证数据
        try{
            validate(CouponValidate::class)->scene('edit')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $data['start_time'] = strtotime($data['start_time']);
        $data['end_time']   = strtotime($data['end_time']);
        $flag = $couponModel->edit($data);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('修改成功');
    }

    // 删除优惠券
    public function couponDel()
    {
        $couponModel = new Coupon();
        $data = input('post.');

        // 验证数据
        try{
            validate(CouponValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $flag = $couponModel->edit(['id' => $data['id'], 'del_time' => time()]);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('删除成功');
    }






    // 渲染购物卡列表页面
    public function card_shop_list()
    {   
        return view();
    }

    // 渲染购物卡添加页面
    public function card_shop_add()
    {   
        $adminModel = new Admin();

        $shopList = $adminModel->getList(['role_id' => 2], 0);

        View::assign('shop_list', $shopList['data']);
        return view();
    }

    // 渲染购物卡编辑页面
    public function card_shop_edit()
    {   
        $data = input('get.');
        $adminModel = new Admin();
        $cardShopModel = new CardShop();

        $info = $cardShopModel->getFind(['id' => $data['id']])['data'];

        $info['type_value_arr'] = [1 => '无限制', 2 => '分类', 3 => '指定商品'];

        $shopList = $adminModel->getList([['id', '<>', $info->getData('admin_id')], ['role_id', '=', 2]], 0);

        if($info->getData('type') == 1){
            $typeValueList = [];
        }else{
            if($info->getData('type') == 2){
                $model = new Cate();
                $field = 'id, name';
                $where[] = ['type', '<>', 5];
            }else if($info->getData('type') == 3){
                $model = new Goods();
                $field = 'id, title as name';
                $where = [];
            }
    
            $typeValueList = $model->getList($where, 0, 0, 0, $field)['data'];
        }

        View::assign('info', $info);
        View::assign('shop_list', $shopList['data']);
        View::assign('type_value_list', $typeValueList);
        return view();
    }

    // 获取购物卡列表
    public function card_shop_data()
    {   
        $cateModel = new Cate();
        $goodsModel = new Goods();
        $cardShopModel = new CardShop();
        $data = input('get.');

        // 验证数据
        try{
            validate(CardShopValidate::class)->scene('list')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $where[] = ['del_time', '=', 0];

        // 搜索条件
        if($data && isset($data['key'])){
            if(!empty($data['key']['name'])){
                $where[] = ['name', 'like', '%' . $data['key']['name'] . '%'];
            }
        }

        $count = $cardShopModel->getNum($where)['data'];

        $field = 'id, admin_id, name, price, time, type, type_value';
        $list = $cardShopModel->getList($where, 1, $data['page'], $data['limit'], $field);

        if($list['code'] != 'ok'){
            $this->error_back('暂无数据~');
        }

        foreach($list['data'] as $k => $v){
            if($v->getData('type') == 2){
                $list['data'][$k]['type_value_name'] = $cateModel->getVal(['id' => $v['type_value']], 'name')['data'];
            }else if($v->getData('type') == 3){
                $list['data'][$k]['type_value_name'] = $goodsModel->getVal(['id' => $v['type_value']], 'title')['data'];
            }else{
                $list['data'][$k]['type_value_name'] = '-';
            }
        }

        $this->success_back('ok', $list['data'], $count);
    }

    // 获取购物卡类型值
    public function getCardShopTypeData(){
        $type = input('type');

        if($type == 2){
            $model = new Cate();
            $field = 'id, name';
            $where[] = ['type', '<>', 5];
        }else{
            $model = new Goods();
            $field = 'id, title as name';
            $where = [];
        }

        $list = $model->getList($where, 0, 0, 0, $field)['data'];

        $this->success_back('ok', $list);
    }

    // 购物卡添加
    public function cardShopAdd()
    {   
        $cardShopModel = new CardShop();
        $data = input('post.');

        // 验证数据
        try{
            validate(CardShopValidate::class)->scene('add')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $flag = $cardShopModel->add($data);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('添加成功');
    }

    // 购物卡信息修改
    public function setCardShopEdit()
    {   
        $cardShopModel = new CardShop();
        $data = input('post.');

        // 验证数据
        try{
            validate(CardShopValidate::class)->scene('edit')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $flag = $cardShopModel->edit($data);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('修改成功');
    }

    // 删除购物卡
    public function cardShopDel()
    {
        $cardShopModel = new CardShop();
        $data = input('post.');

        // 验证数据
        try{
            validate(CardShopValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $flag = $cardShopModel->edit(['id' => $data['id'], 'del_time' => time()]);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('删除成功');
    }




    /** 渲染礼品包列表页面 */
    public function gift_list(){
        return view();
    }

    /** 渲染礼品包添加页面 */
    public function gift_add(){
        $adminModel = new Admin();
        $shopList = $adminModel->getList(['role_id' => 2], 0);

        View::assign('shop_list', $shopList['data']);
        return view();
    }

    /** 渲染礼品包编辑页面 */
    public function gift_edit(){
        $giftModel = new Gift();
        $cardModel = new Card();
        $goodsModel = new Goods();
        $adminModel = new Admin();

        $data = input('');

        $gift_info = $giftModel->getFind(['id' => $data['id']])['data'];
        $gift_info['shop_name']  = $adminModel->getVal(['id' => $gift_info['admin_id']], 'nickname')['data'];

        $goods_ids = [];
        $card_ids  = [];

        foreach($gift_info['gifts'] as $k => $v){
            if($v['type'] == 1){
                $goods_ids[] = $v['aim_id'];
            }else{
                $card_ids[] = $v['aim_id'];
            }
        }

        $gift_info['goods_ids'] = $goods_ids;
        $gift_info['card_ids']  = $card_ids;
        unset($gift_info['gifts']);

        $shopList = $adminModel->getList([['id', '<>', $gift_info['admin_id']], ['role_id', '=', 2]], 0);

        $card_list  = $cardModel->getList(['admin_id' => $gift_info['admin_id']], 0, 0, 0, 'id, name')['data'];
        $goods_list = $goodsModel->getList(['admin_id' => $gift_info['admin_id']], 0, 0, 0, 'id, title')['data'];

        View::assign('shop_list', $shopList['data']);
        View::assign('info', $gift_info);
        View::assign('card_list', $card_list);
        View::assign('goods_list', $goods_list);
        return view();
    }

    /** 获取礼品数据 */
    public function gifts(){
        $cardModel  = new Card();
        $goodsModel = new Goods();
        $giftGoodsModel = new GiftGoods();
        $data = input('');

        $card_list  = $cardModel->getList(['admin_id' => $data['admin_id']], 0, 0, 0, 'id, name')['data'];
        $goods_list = $goodsModel->getList(['admin_id' => $data['admin_id']], 0, 0, 0, 'id, title')['data'];

        if(isset($data['gift_id'])){
            foreach($card_list as $k => $v){
                $card_flag = $giftGoodsModel->getFind(['gift_id' => $data['gift_id'], 'aim_id' => $v['id'], 'type' => 2], 'id');
    
                if($card_flag['code'] != 'ok'){
                    $v['is_checked'] = 0;
                }else{
                    $v['is_checked'] = 1;
                } 
            }
    
            foreach($goods_list as $k => $v){
                $goods_flag = $giftGoodsModel->getFind(['gift_id' => $data['gift_id'], 'aim_id' => $v['id'], 'type' => 1], 'id');
    
                if($goods_flag['code'] != 'ok'){
                    $v['is_checked'] = 0;
                }else{
                    $v['is_checked'] = 1;
                } 
            }
        }

        $this->success_back('ok', ['card_list' => $card_list, 'goods_list' => $goods_list]);
    }

    /** 礼品包数据列表 */
    public function gift_data(){
        $giftModel  = new Gift();
        $cardModel  = new Card();
        $goodsModel  = new Goods();
        $adminModel = new Admin();
        $data = input('');

        // 验证数据
        try{
            validate(GiftValidate::class)->scene('list')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $where[] = ['del_time', '=', 0];

        // 搜索条件
        if($data && isset($data['key'])){
            if(!empty($data['key']['name'])){
                $where[] = ['name', 'like', '%' . $data['key']['name'] . '%'];
            }
        }

        $count = $giftModel->getNum($where)['data'];

        $list = $giftModel->getGoodsList($where, $data['page'], $data['limit']);

        if($list['code'] != 'ok'){
            $this->error_back('暂无数据~');
        }

        foreach($list['data'] as $k => $v){
            $v['shop_name']  = $adminModel->getVal(['id' => $v['admin_id']], 'nickname')['data'];

            $gift_content = '';
            foreach($v['gifts'] as $key => $val){
                if($val['type'] == 1){
                    $gift_goods_title = $goodsModel->getVal(['id' => $val['aim_id']], 'title')['data'];
                }else{
                    $gift_goods_title = $cardModel->getVal(['id' => $val['aim_id']], 'name')['data'];
                }

                $gift_content .= $gift_goods_title . ', ';
            }

            $v['gift'] = $gift_content;
            unset($v['gifts']);
        }

        $this->success_back('ok', $list['data'], $count);
    }

    /** 礼品包添加 */
    public function gift_add_data()
    {   
        $giftModel = new Gift();
        $giftGoodsModel = new GiftGoods();

        $data = input('post.');
        $data['small_img'] = request()->file('small_img');

        // 验证数据
        try{
            validate(GiftValidate::class)->scene('add')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        if(empty($data['card_id']) && empty($data['goods_id'])){
            $this->error_back('礼品不能为空');
        }

        // 开启事务
        Db::startTrans();

        try{
            $gift_add = [
                'admin_id'  => $data['admin_id'],
                'name'      => $data['name'],
                'price'     => $data['price'],
                'small_img' => fileUp($data['small_img'], 'gift'),
            ];

            $flag = $giftModel->add($gift_add);

            if($flag['code'] != 'ok'){
                $this->error_back($flag['msg']);
            }

            $gift_goods_arr = [];

            if(!empty($data['card_id'])){
                $card_id_arr = explode(',', $data['card_id']);
                array_pop($card_id_arr);

                foreach($card_id_arr as $v){
                    $gift_goods_arr[] = [
                        'gift_id' => $flag['data'],
                        'aim_id'  => $v,
                        'type'    => 2
                    ];
                }
            }

            if(!empty($data['goods_id'])){
                $goods_id_arr = explode(',', $data['goods_id']);
                array_pop($goods_id_arr);

                foreach($goods_id_arr as $v){
                    $gift_goods_arr[] = [
                        'gift_id' => $flag['data'],
                        'aim_id'  => $v,
                        'type'    => 1
                    ];
                }
            }

            $gift_goods_flag = $giftGoodsModel->addAll($gift_goods_arr);

            if($gift_goods_flag['code'] != 'ok'){
                abort(40001, '礼品新增异常');
            }

            // 提交事务
            Db::commit();
        }catch(ValidateException $e){
            // 回滚事务
            Db::rollback();
        }

        $this->success_back('添加成功');
    }

    /** 礼品包编辑 */
    public function gift_edit_data()
    {   
        $giftModel = new Gift();
        $giftGoodsModel = new GiftGoods();

        $data = input('post.');
        $data['small_img'] = request()->file('small_img');

        if($data['small_img']){
            $field = 'edit_img';
        }else{
            $field = 'edit';
        }

        // 验证数据
        try{
            validate(GiftValidate::class)->scene($field)->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        if(empty($data['card_id']) && empty($data['goods_id'])){
            $this->error_back('礼品不能为空');
        }

        // 开启事务
        Db::startTrans();

        try{
            $gift_edit = [
                'id'        => $data['id'],
                'admin_id'  => $data['admin_id'],
                'name'      => $data['name'],
                'price'     => $data['price'],
            ];

            if($data['small_img']){
                $gift_edit['small_img'] = fileUp($data['small_img'], 'gift');
            }

            $flag = $giftModel->edit($gift_edit);

            if($flag['code'] != 'ok'){
                $this->error_back($flag['msg']);
            }

            $gift_goods_del = $giftGoodsModel->del(['gift_id' => $data['id']]);

            if($gift_goods_del['code'] != 'ok'){
                abort(40001, '礼品处理异常');
            }

            $gift_goods_arr = [];

            if(!empty($data['card_id'])){
                $card_id_arr = explode(',', $data['card_id']);
                array_pop($card_id_arr);

                foreach($card_id_arr as $v){
                    $gift_goods_arr[] = [
                        'gift_id' => $data['id'],
                        'aim_id'  => $v,
                        'type'    => 2
                    ];
                }
            }

            if(!empty($data['goods_id'])){
                $goods_id_arr = explode(',', $data['goods_id']);
                array_pop($goods_id_arr);

                foreach($goods_id_arr as $v){
                    $gift_goods_arr[] = [
                        'gift_id' => $data['id'],
                        'aim_id'  => $v,
                        'type'    => 1
                    ];
                }
            }

            $gift_goods_flag = $giftGoodsModel->addAll($gift_goods_arr);

            if($gift_goods_flag['code'] != 'ok'){
                abort(40001, '礼品新增异常');
            }

            // 提交事务
            Db::commit();
        }catch(ValidateException $e){
            // 回滚事务
            Db::rollback();
        }

        $this->success_back('编辑成功');
    }

    // 删除礼品包
    public function gift_del()
    {
        $giftModel = new Gift();
        $data = input('');

        // 验证数据
        try{
            validate(GiftValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $flag = $giftModel->edit(['id' => $data['id'], 'del_time' => time()]);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('删除成功');
    }
}
